import * as Sentry from '@sentry/vue';
import { importCommonConfig } from '@/config/axios.config';
import { App } from 'vue';
import { Router } from 'vue-router';

function getEnvironment() {
    const href = window.location.href;
    const domain = new URL(href).hostname;

    // 定义环境识别的正则表达式
    const localPatterns = [/^local\./, /^localhost/, /^\d{1,3}(\.\d{1,3}){3}$/]; // 包含localhost和标准IPv4格式
    const devPattern = /-dev\./;
    const qaPattern = /-qa\./;

    // 判断环境
    if (localPatterns.some(pattern => pattern.test(domain))) {
        return 'local';
    } else if (devPattern.test(domain)) {
        return 'dev';
    } else if (qaPattern.test(domain)) {
        return 'qa';
    } else {
        // 如果前面的模式都不匹配，默认为生产环境
        return 'production';
    }
}

async function initSentry(app: App<Element>, router: Router) {
    const curEnv = process.env.APP_DEPLOY_ENV as string;
    const curConfig = await importCommonConfig();
    const sentryConfig = curConfig[curEnv]?.sentry || {};
    Sentry.init({
        app,
        dsn: sentryConfig?.dsn,
        release: sentryConfig?.version,
        environment: getEnvironment(),
        integrations: [
            new Sentry.BrowserTracing({
                routingInstrumentation: Sentry.vueRouterInstrumentation(router),
            }),
            new Sentry.Replay(),
        ],
    });
}

export { initSentry };
